package
{
	public class XMLHandler
	{
		import flash.events.Event;
		import flash.filesystem.File;
		import flash.filesystem.FileMode;
		import flash.filesystem.FileStream;	
		
		private var xmlFile:File;
		private var xmlObj:XML = new XML();
		private var dataString:String;
		
		//Constructor reading a XML file to XML object.
		public function XMLLoad(xmlFile:File):void
		{
			this.xmlFile=xmlFile;
			loadXML();
			
		}
		
		public function loadXML():void
		{
			var stream:FileStream = new FileStream();
			stream.open(this.xmlFile, FileMode.READ);
			xmlObj = XML(stream.readUTFBytes(stream.bytesAvailable));
			stream.close()
		}
		
		//Function for saving all variables to a XML file.
		public function saveXML(e:Event):void
		{
			var f:File = File(e.target);
			
			xmlObj.ProjectName = f.name;
			
			var stream:FileStream = new FileStream();
			if(f.extension == null){
				trace("Setting file extension to .xml");
				stream.open(f.resolvePath(f.nativePath + ".xml"), FileMode.WRITE);
			}
			else{
				trace("File extension already .xml");
				stream.open(f, FileMode.WRITE);
			}
			stream.writeUTFBytes(xmlObj);
			stream.addEventListener(Event.CLOSE, onDataSaved);
			stream.close;
		}
		
		public function save():void{
			var stream:FileStream = new FileStream();
			stream.open(xmlFile, FileMode.WRITE);
			
			stream.writeUTFBytes(xmlObj);
			stream.addEventListener(Event.CLOSE, onDataSaved);
			stream.close;
		}
		
		
		
		private function onDataSaved(event:Event):void
		{
			loadXML();
			
		}
		
		public function getXML():XML
		{
			return xmlObj;
		}
		
	}
	
		
	
}